<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>数据仪表盘 - 宠物狗识别系统</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.8/dist/chart.umd.min.js"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#4F46E5',
                        secondary: '#10B981',
                        danger: '#EF4444',
                        warning: '#F59E0B',
                        info: '#3B82F6',
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .shadow-soft {
                box-shadow: 0 2px 15px rgba(0, 0, 0, 0.05);
            }
            .transition-all-300 {
                transition: all 0.3s ease;
            }
            .skeleton {
                background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
                background-size: 200% 100%;
                animation: skeleton-loading 1.5s infinite;
            }
            @keyframes skeleton-loading {
                0% { background-position: 200% 0; }
                100% { background-position: -200% 0; }
            }
        }
    </style>
</head>
<body class="bg-gray-50 min-h-screen flex flex-col">
    <header class="bg-white shadow-sm">
        <div class="container mx-auto px-4 py-4 flex justify-between items-center">
            <h1 class="text-2xl font-bold text-primary flex items-center">
                <i class="fa fa-paw mr-2"></i>宠物狗识别系统
            </h1>
            <nav>
                <ul class="flex space-x-6">
                    <li><a href="#" class="text-primary font-medium border-b-2 border-primary pb-1">数据仪表盘</a></li>
                    <li><a href="image-upload.html" class="text-gray-600 hover:text-primary transition-colors">图片上传</a></li>
                    <li><a href="#about" class="text-gray-600 hover:text-primary transition-colors">关于我们</a></li>
                </ul>
            </nav>
        </div>
    </header>

    <main class="flex-grow container mx-auto px-4 py-8">
        <!-- 页面标题和操作栏 -->
        <div class="flex flex-col md:flex-row justify-between items-start md:items-center mb-6">
            <div>
                <h2 class="text-xl md:text-2xl font-bold text-gray-800 mb-1">数据仪表盘</h2>
                <p class="text-gray-500 text-sm">实时监控系统核心指标和趋势</p>
            </div>
            <div class="mt-4 md:mt-0 flex space-x-3">
                <!-- 时间筛选器 -->
                <div class="relative">
                    <button id="date-range-btn" class="bg-white border border-gray-300 rounded-lg px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 transition-all-300 flex items-center">
                        <i class="fa fa-calendar-o mr-2"></i>
                        <span id="date-range-text">近7天</span>
                        <i class="fa fa-chevron-down ml-2 text-xs"></i>
                    </button>
                    <div id="date-range-dropdown" class="hidden absolute right-0 mt-2 w-80 bg-white rounded-lg shadow-lg z-10 border border-gray-200">
                        <!-- 预设时间选项 -->
                        <div class="p-3 border-b border-gray-200">
                            <h4 class="text-xs font-medium text-gray-500 mb-2">快速选择</h4>
                            <div class="grid grid-cols-2 gap-2">
                                <button class="date-option px-3 py-1.5 text-sm rounded hover:bg-gray-100 transition-colors" data-range="today">今天</button>
                                <button class="date-option px-3 py-1.5 text-sm rounded hover:bg-gray-100 transition-colors" data-range="yesterday">昨天</button>
                                <button class="date-option px-3 py-1.5 text-sm rounded hover:bg-gray-100 transition-colors" data-range="7days">近7天</button>
                                <button class="date-option px-3 py-1.5 text-sm rounded hover:bg-gray-100 transition-colors" data-range="30days">近30天</button>
                                <button class="date-option px-3 py-1.5 text-sm rounded hover:bg-gray-100 transition-colors" data-range="90days">近90天</button>
                                <button class="date-option px-3 py-1.5 text-sm rounded hover:bg-gray-100 transition-colors" data-range="365days">近一年</button>
                            </div>
                        </div>
                        <!-- 自定义时间范围 -->
                        <div class="p-3">
                            <h4 class="text-xs font-medium text-gray-500 mb-2">自定义范围</h4>
                            <div class="flex items-center space-x-2 mb-3">
                                <input type="date" id="custom-start-date" class="flex-1 px-3 py-2 text-sm border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary">
                                <span class="text-gray-400">至</span>
                                <input type="date" id="custom-end-date" class="flex-1 px-3 py-2 text-sm border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary">
                            </div>
                            <div class="flex justify-end space-x-2">
                                <button id="cancel-date-btn" class="px-3 py-1.5 text-sm text-gray-600 hover:bg-gray-100 rounded transition-colors">取消</button>
                                <button id="apply-date-btn" class="px-3 py-1.5 text-sm text-white bg-primary rounded hover:bg-primary/90 transition-colors">应用</button>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- 数据导出按钮 -->
                <button id="export-btn" class="bg-secondary hover:bg-secondary/90 text-white font-medium px-4 py-2 rounded-lg flex items-center shadow-sm hover:shadow transition-all-300">
                    <i class="fa fa-download mr-2"></i>
                    <span>导出数据</span>
                </button>
                <!-- 刷新按钮 -->
                <button id="refresh-btn" class="bg-white border border-gray-300 hover:bg-gray-50 text-gray-700 font-medium px-3 py-2 rounded-lg flex items-center shadow-sm hover:shadow transition-all-300">
                    <i class="fa fa-refresh"></i>
                </button>
            </div>
        </div>

        <!-- 核心指标数字卡片 -->
        <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
            <!-- 用户总数卡片 -->
            <div class="bg-white rounded-xl shadow-soft p-6 transition-all-300 hover:shadow-md">
                <div class="flex justify-between items-start mb-4">
                    <div>
                        <p class="text-gray-500 text-sm mb-1">总用户数</p>
                        <h3 id="total-users" class="text-3xl font-bold text-gray-800 skeleton h-10 w-24"></h3>
                    </div>
                    <div class="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center text-primary">
                        <i class="fa fa-users"></i>
                    </div>
                </div>
                <div class="flex items-center text-sm">
                    <span class="text-secondary font-medium flex items-center">
                        <i class="fa fa-arrow-up mr-1"></i>
                        <span id="user-growth-rate">--</span>
                    </span>
                    <span class="text-gray-500 ml-2">较上周期</span>
                </div>
            </div>

            <!-- 今日新增用户卡片 -->
            <div class="bg-white rounded-xl shadow-soft p-6 transition-all-300 hover:shadow-md">
                <div class="flex justify-between items-start mb-4">
                    <div>
                        <p class="text-gray-500 text-sm mb-1">今日新增用户</p>
                        <h3 id="today-new-users" class="text-3xl font-bold text-gray-800 skeleton h-10 w-24"></h3>
                    </div>
                    <div class="w-10 h-10 rounded-full bg-info/10 flex items-center justify-center text-info">
                        <i class="fa fa-user-plus"></i>
                    </div>
                </div>
                <div class="flex items-center text-sm">
                    <span class="text-secondary font-medium flex items-center">
                        <i class="fa fa-arrow-up mr-1"></i>
                        <span id="new-user-growth-rate">--</span>
                    </span>
                    <span class="text-gray-500 ml-2">较昨日</span>
                </div>
            </div>

            <!-- 总内容数卡片 -->
            <div class="bg-white rounded-xl shadow-soft p-6 transition-all-300 hover:shadow-md">
                <div class="flex justify-between items-start mb-4">
                    <div>
                        <p class="text-gray-500 text-sm mb-1">总内容数</p>
                        <h3 id="total-content" class="text-3xl font-bold text-gray-800 skeleton h-10 w-24"></h3>
                    </div>
                    <div class="w-10 h-10 rounded-full bg-secondary/10 flex items-center justify-center text-secondary">
                        <i class="fa fa-file-text"></i>
                    </div>
                </div>
                <div class="flex items-center text-sm">
                    <span class="text-secondary font-medium flex items-center">
                        <i class="fa fa-arrow-up mr-1"></i>
                        <span id="content-growth-rate">--</span>
                    </span>
                    <span class="text-gray-500 ml-2">较上周期</span>
                </div>
            </div>

            <!-- 总识别次数卡片 -->
            <div class="bg-white rounded-xl shadow-soft p-6 transition-all-300 hover:shadow-md">
                <div class="flex justify-between items-start mb-4">
                    <div>
                        <p class="text-gray-500 text-sm mb-1">总识别次数</p>
                        <h3 id="total-recognitions" class="text-3xl font-bold text-gray-800 skeleton h-10 w-24"></h3>
                    </div>
                    <div class="w-10 h-10 rounded-full bg-warning/10 flex items-center justify-center text-warning">
                        <i class="fa fa-eye"></i>
                    </div>
                </div>
                <div class="flex items-center text-sm">
                    <span class="text-secondary font-medium flex items-center">
                        <i class="fa fa-arrow-up mr-1"></i>
                        <span id="recognition-growth-rate">--</span>
                    </span>
                    <span class="text-gray-500 ml-2">较上周期</span>
                </div>
            </div>
        </div>

        <!-- 图表展示区域 -->
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-8">
            <!-- 用户增长趋势折线图 -->
            <div class="lg:col-span-2 bg-white rounded-xl shadow-soft p-6 transition-all-300">
                <div class="flex justify-between items-center mb-6">
                    <h3 class="text-lg font-bold text-gray-800">用户与内容趋势</h3>
                    <div class="flex space-x-2">
                        <button class="chart-filter-btn px-3 py-1 text-sm rounded-full bg-primary text-white" data-type="all">全部</button>
                        <button class="chart-filter-btn px-3 py-1 text-sm rounded-full bg-gray-100 text-gray-600 hover:bg-gray-200 transition-colors" data-type="users">用户</button>
                        <button class="chart-filter-btn px-3 py-1 text-sm rounded-full bg-gray-100 text-gray-600 hover:bg-gray-200 transition-colors" data-type="content">内容</button>
                    </div>
                </div>
                <div class="h-80">
                    <div id="trend-chart-container" class="w-full h-full">
                        <canvas id="trend-chart"></canvas>
                    </div>
                </div>
            </div>

            <!-- 社区活跃度饼图 -->
            <div class="bg-white rounded-xl shadow-soft p-6 transition-all-300">
                <h3 class="text-lg font-bold text-gray-800 mb-6">社区活跃度分布</h3>
                <div class="h-80">
                    <div id="community-pie-chart-container" class="w-full h-full">
                        <canvas id="community-pie-chart"></canvas>
                    </div>
                </div>
                <div class="mt-4 grid grid-cols-2 gap-4">
                    <div class="flex items-center p-3 bg-gray-50 rounded-lg">
                        <div class="w-3 h-3 rounded-full bg-primary mr-2"></div>
                        <span class="text-sm text-gray-600">活跃社区</span>
                        <span class="ml-auto font-medium text-gray-800" id="active-community-count">--</span>
                    </div>
                    <div class="flex items-center p-3 bg-gray-50 rounded-lg">
                        <div class="w-3 h-3 rounded-full bg-gray-300 mr-2"></div>
                        <span class="text-sm text-gray-600">非活跃社区</span>
                        <span class="ml-auto font-medium text-gray-800" id="inactive-community-count">--</span>
                    </div>
                </div>
            </div>
        </div>

        <!-- 内容分布和AI识别数据 -->
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
            <!-- 内容分布柱状图 -->
            <div class="bg-white rounded-xl shadow-soft p-6 transition-all-300">
                <h3 class="text-lg font-bold text-gray-800 mb-6">内容发布分布</h3>
                <div class="h-80">
                    <div id="content-distribution-chart-container" class="w-full h-full">
                        <canvas id="content-distribution-chart"></canvas>
                    </div>
                </div>
            </div>

            <!-- AI识别数据面板 -->
            <div class="bg-white rounded-xl shadow-soft p-6 transition-all-300">
                <h3 class="text-lg font-bold text-gray-800 mb-6">AI识别数据</h3>
                <div class="grid grid-cols-2 gap-4 mb-6">
                    <div class="p-4 bg-gray-50 rounded-lg">
                        <p class="text-sm text-gray-500 mb-1">今日识别次数</p>
                        <p class="text-2xl font-bold text-gray-800" id="today-recognitions">--</p>
                    </div>
                    <div class="p-4 bg-gray-50 rounded-lg">
                        <p class="text-sm text-gray-500 mb-1">识别准确率</p>
                        <p class="text-2xl font-bold text-gray-800" id="recognition-accuracy">--</p>
                    </div>
                    <div class="p-4 bg-gray-50 rounded-lg">
                        <p class="text-sm text-gray-500 mb-1">拦截率</p>
                        <p class="text-2xl font-bold text-gray-800" id="intercept-rate">--</p>
                    </div>
                    <div class="p-4 bg-gray-50 rounded-lg">
                        <p class="text-sm text-gray-500 mb-1">平均识别时间</p>
                        <p class="text-2xl font-bold text-gray-800" id="avg-recognition-time">--</p>
                    </div>
                </div>
                <div class="h-48">
                    <div id="recognition-breed-chart-container" class="w-full h-full">
                        <canvas id="recognition-breed-chart"></canvas>
                    </div>
                </div>
            </div>
        </div>
    </main>

    <footer class="bg-white border-t border-gray-200 py-6">
        <div class="container mx-auto px-4">
            <div class="text-center text-gray-500 text-sm">
                <p>© 2023 宠物狗识别系统. 保留所有权利.</p>
            </div>
        </div>
    </footer>

    <!-- 错误提示弹窗 -->
    <div id="error-toast" class="fixed top-4 right-4 max-w-sm bg-red-50 text-danger p-4 rounded-lg shadow-lg transform transition-all duration-300 translate-y-[-100px] opacity-0 z-50 flex items-start">
        <i class="fa fa-exclamation-circle text-xl mr-3 mt-0.5"></i>
        <div>
            <h4 class="font-medium text-danger mb-1">错误提示</h4>
            <p id="error-toast-message" class="text-sm">操作失败，请稍后重试</p>
        </div>
        <button id="close-error-toast" class="ml-4 text-gray-400 hover:text-gray-600">
            <i class="fa fa-times"></i>
        </button>
    </div>

    <!-- 成功提示弹窗 -->
    <div id="success-toast" class="fixed top-4 right-4 max-w-sm bg-green-50 text-green-700 p-4 rounded-lg shadow-lg transform transition-all duration-300 translate-y-[-100px] opacity-0 z-50 flex items-start">
        <i class="fa fa-check-circle text-xl mr-3 mt-0.5"></i>
        <div>
            <h4 class="font-medium text-green-700 mb-1">操作成功</h4>
            <p id="success-toast-message" class="text-sm">数据加载成功</p>
        </div>
        <button id="close-success-toast" class="ml-4 text-gray-400 hover:text-gray-600">
            <i class="fa fa-times"></i>
        </button>
    </div>

    <!-- 加载遮罩层 -->
    <div id="loading-overlay" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
        <div class="bg-white rounded-lg p-6 shadow-xl flex flex-col items-center">
            <div class="w-12 h-12 border-4 border-primary border-t-transparent rounded-full animate-spin mb-4"></div>
            <p id="loading-text" class="text-gray-700 font-medium">正在加载数据...</p>
        </div>
    </div>

    <script>
        // DOM元素获取
        const dateRangeBtn = document.getElementById('date-range-btn');
        const dateRangeDropdown = document.getElementById('date-range-dropdown');
        const dateRangeText = document.getElementById('date-range-text');
        const dateOptions = document.querySelectorAll('.date-option');
        const customStartDate = document.getElementById('custom-start-date');
        const customEndDate = document.getElementById('custom-end-date');
        const cancelDateBtn = document.getElementById('cancel-date-btn');
        const applyDateBtn = document.getElementById('apply-date-btn');
        const exportBtn = document.getElementById('export-btn');
        const refreshBtn = document.getElementById('refresh-btn');
        const errorToast = document.getElementById('error-toast');
        const errorToastMessage = document.getElementById('error-toast-message');
        const closeErrorToast = document.getElementById('close-error-toast');
        const successToast = document.getElementById('success-toast');
        const successToastMessage = document.getElementById('success-toast-message');
        const closeSuccessToast = document.getElementById('close-success-toast');
        const loadingOverlay = document.getElementById('loading-overlay');
        const loadingText = document.getElementById('loading-text');
        const chartFilterBtns = document.querySelectorAll('.chart-filter-btn');

        // 初始化日期选择器
        const today = new Date();
        const weekAgo = new Date();
        weekAgo.setDate(weekAgo.getDate() - 6);

        const formatDate = (date) => {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            return `${year}-${month}-${day}`;
        };

        customEndDate.value = formatDate(today);
        customStartDate.value = formatDate(weekAgo);

        // 日期范围选择器逻辑
        dateRangeBtn.addEventListener('click', () => {
            dateRangeDropdown.classList.toggle('hidden');
        });

        document.addEventListener('click', (e) => {
            if (!dateRangeBtn.contains(e.target) && !dateRangeDropdown.contains(e.target)) {
                dateRangeDropdown.classList.add('hidden');
            }
        });

        // 预设日期选项点击事件
        dateOptions.forEach(option => {
            option.addEventListener('click', () => {
                const range = option.getAttribute('data-range');
                let startDate, endDate, displayText;
                const today = new Date();
                
                switch(range) {
                    case 'today':
                        startDate = formatDate(today);
                        endDate = formatDate(today);
                        displayText = '今天';
                        break;
                    case 'yesterday':
                        const yesterday = new Date(today);
                        yesterday.setDate(yesterday.getDate() - 1);
                        startDate = formatDate(yesterday);
                        endDate = formatDate(yesterday);
                        displayText = '昨天';
                        break;
                    case '7days':
                        const weekAgo = new Date(today);
                        weekAgo.setDate(weekAgo.getDate() - 6);
                        startDate = formatDate(weekAgo);
                        endDate = formatDate(today);
                        displayText = '近7天';
                        break;
                    case '30days':
                        const monthAgo = new Date(today);
                        monthAgo.setDate(monthAgo.getDate() - 29);
                        startDate = formatDate(monthAgo);
                        endDate = formatDate(today);
                        displayText = '近30天';
                        break;
                    case '90days':
                        const quarterAgo = new Date(today);
                        quarterAgo.setDate(quarterAgo.getDate() - 89);
                        startDate = formatDate(quarterAgo);
                        endDate = formatDate(today);
                        displayText = '近90天';
                        break;
                    case '365days':
                        const yearAgo = new Date(today);
                        yearAgo.setDate(yearAgo.getDate() - 364);
                        startDate = formatDate(yearAgo);
                        endDate = formatDate(today);
                        displayText = '近一年';
                        break;
                    default:
                        startDate = formatDate(weekAgo);
                        endDate = formatDate(today);
                        displayText = '近7天';
                }
                
                customStartDate.value = startDate;
                customEndDate.value = endDate;
                dateRangeText.textContent = displayText;
                dateRangeDropdown.classList.add('hidden');
                
                // 加载新数据
                loadDashboardData(startDate, endDate);
            });
        });

        // 应用自定义日期范围
        applyDateBtn.addEventListener('click', () => {
            const startDate = customStartDate.value;
            const endDate = customEndDate.value;
            
            if (!startDate || !endDate) {
                showErrorToast('请选择有效的日期范围');
                return;
            }
            
            if (new Date(startDate) > new Date(endDate)) {
                showErrorToast('开始日期不能晚于结束日期');
                return;
            }
            
            const daysDiff = Math.ceil((new Date(endDate) - new Date(startDate)) / (1000 * 60 * 60 * 24));
            if (daysDiff > 365) {
                showErrorToast('时间范围跨度不能超过365天');
                return;
            }
            
            // 计算显示文本
            let displayText;
            if (startDate === endDate) {
                displayText = '自定义日期';
            } else {
                const start = startDate.split('-').slice(1).join('-');
                const end = endDate.split('-').slice(1).join('-');
                displayText = `${start} 至 ${end}`;
            }
            
            dateRangeText.textContent = displayText;
            dateRangeDropdown.classList.add('hidden');
            
            // 加载新数据
            loadDashboardData(startDate, endDate);
        });

        // 取消自定义日期范围
        cancelDateBtn.addEventListener('click', () => {
            dateRangeDropdown.classList.add('hidden');
        });

        // 刷新按钮点击事件
        refreshBtn.addEventListener('click', () => {
            const startDate = customStartDate.value;
            const endDate = customEndDate.value;
            loadDashboardData(startDate, endDate);
        });

        // 导出按钮点击事件
        exportBtn.addEventListener('click', async () => {
            const startDate = customStartDate.value;
            const endDate = customEndDate.value;
            
            try {
                showLoading('正在准备导出文件...');
                
                // 发送导出请求
                const response = await fetch(`/api/admin/dashboard/export?startDate=${startDate}&endDate=${endDate}&dataType=all`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
                
                if (!response.ok) {
                    const errorData = await response.json();
                    throw new Error(errorData.message || '文件导出异常，请检查数据量或稍后重试');
                }
                
                // 处理文件下载
                const blob = await response.blob();
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = `数据统计_${startDate}_${endDate}.xlsx`;
                document.body.appendChild(a);
                a.click();
                window.URL.revokeObjectURL(url);
                document.body.removeChild(a);
                
                hideLoading();
                showSuccessToast('数据导出成功');
            } catch (error) {
                hideLoading();
                showErrorToast(error.message || '文件导出异常，请检查数据量或稍后重试');
            }
        });

        // 图表筛选按钮点击事件
        chartFilterBtns.forEach(btn => {
            btn.addEventListener('click', () => {
                chartFilterBtns.forEach(b => {
                    b.classList.remove('bg-primary', 'text-white');
                    b.classList.add('bg-gray-100', 'text-gray-600');
                });
                btn.classList.remove('bg-gray-100', 'text-gray-600');
                btn.classList.add('bg-primary', 'text-white');
                
                // 更新趋势图显示
                updateTrendChart(btn.getAttribute('data-type'));
            });
        });

        // 错误提示弹窗
        function showErrorToast(message) {
            errorToastMessage.textContent = message;
            errorToast.classList.remove('translate-y-[-100px]', 'opacity-0');
            
            setTimeout(() => {
                hideErrorToast();
            }, 5000);
        }

        function hideErrorToast() {
            errorToast.classList.add('translate-y-[-100px]', 'opacity-0');
        }

        // 成功提示弹窗
        function showSuccessToast(message) {
            successToastMessage.textContent = message;
            successToast.classList.remove('translate-y-[-100px]', 'opacity-0');
            
            setTimeout(() => {
                hideSuccessToast();
            }, 3000);
        }

        function hideSuccessToast() {
            successToast.classList.add('translate-y-[-100px]', 'opacity-0');
        }

        // 加载遮罩层
        function showLoading(text = '正在加载数据...') {
            loadingText.textContent = text;
            loadingOverlay.classList.remove('hidden');
        }

        function hideLoading() {
            loadingOverlay.classList.add('hidden');
        }

        // 初始化图表
        let trendChart, communityPieChart, contentDistributionChart, recognitionBreedChart;

        function initCharts() {
            // 用户与内容趋势折线图
            const trendCtx = document.getElementById('trend-chart').getContext('2d');
            trendChart = new Chart(trendCtx, {
                type: 'line',
                data: {
                    labels: [],
                    datasets: [
                        {
                            label: '新增用户',
                            data: [],
                            borderColor: '#4F46E5',
                            backgroundColor: 'rgba(79, 70, 229, 0.1)',
                            borderWidth: 2,
                            tension: 0.3,
                            fill: true
                        },
                        {
                            label: '新增内容',
                            data: [],
                            borderColor: '#10B981',
                            backgroundColor: 'rgba(16, 185, 129, 0.1)',
                            borderWidth: 2,
                            tension: 0.3,
                            fill: true
                        },
                        {
                            label: '识别次数',
                            data: [],
                            borderColor: '#F59E0B',
                            backgroundColor: 'rgba(245, 158, 11, 0.1)',
                            borderWidth: 2,
                            tension: 0.3,
                            fill: true
                        }
                    ]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    interaction: {
                        mode: 'index',
                        intersect: false,
                    },
                    plugins: {
                        legend: {
                            position: 'top',
                            labels: {
                                usePointStyle: true,
                                padding: 20
                            }
                        },
                        tooltip: {
                            backgroundColor: 'rgba(0, 0, 0, 0.7)',
                            padding: 10,
                            cornerRadius: 8,
                            titleFont: {
                                size: 14
                            },
                            bodyFont: {
                                size: 12
                            }
                        }
                    },
                    scales: {
                        x: {
                            grid: {
                                display: false
                            },
                            ticks: {
                                maxRotation: 45,
                                minRotation: 45
                            }
                        },
                        y: {
                            beginAtZero: true,
                            grid: {
                                color: 'rgba(0, 0, 0, 0.05)'
                            },
                            ticks: {
                                callback: function(value) {
                                    if (value >= 1000) {
                                        return (value / 1000) + 'k';
                                    }
                                    return value;
                                }
                            }
                        }
                    }
                }
            });

            // 社区活跃度饼图
            const communityPieCtx = document.getElementById('community-pie-chart').getContext('2d');
            communityPieChart = new Chart(communityPieCtx, {
                type: 'doughnut',
                data: {
                    labels: ['活跃社区', '非活跃社区'],
                    datasets: [{
                        data: [0, 0],
                        backgroundColor: ['#4F46E5', '#D1D5DB'],
                        borderWidth: 0,
                        hoverOffset: 4
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    cutout: '70%',
                    plugins: {
                        legend: {
                            position: 'bottom',
                            labels: {
                                usePointStyle: true,
                                padding: 20
                            }
                        },
                        tooltip: {
                            backgroundColor: 'rgba(0, 0, 0, 0.7)',
                            padding: 10,
                            cornerRadius: 8
                        }
                    }
                }
            });

            // 内容分布柱状图
            const contentDistributionCtx = document.getElementById('content-distribution-chart').getContext('2d');
            contentDistributionChart = new Chart(contentDistributionCtx, {
                type: 'bar',
                data: {
                    labels: [],
                    datasets: [
                        {
                            label: '帖子',
                            data: [],
                            backgroundColor: '#4F46E5',
                            borderRadius: 4
                        },
                        {
                            label: '评论',
                            data: [],
                            backgroundColor: '#3B82F6',
                            borderRadius: 4
                        },
                        {
                            label: '点赞',
                            data: [],
                            backgroundColor: '#10B981',
                            borderRadius: 4
                        }
                    ]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'top',
                            labels: {
                                usePointStyle: true,
                                padding: 20
                            }
                        },
                        tooltip: {
                            backgroundColor: 'rgba(0, 0, 0, 0.7)',
                            padding: 10,
                            cornerRadius: 8
                        }
                    },
                    scales: {
                        x: {
                            grid: {
                                display: false
                            },
                            ticks: {
                                maxRotation: 45,
                                minRotation: 45
                            }
                        },
                        y: {
                            beginAtZero: true,
                            grid: {
                                color: 'rgba(0, 0, 0, 0.05)'
                            }
                        }
                    },
                    barPercentage: 0.6,
                    categoryPercentage: 0.7
                }
            });

            // 识别品种分布图
            const recognitionBreedCtx = document.getElementById('recognition-breed-chart').getContext('2d');
            recognitionBreedChart = new Chart(recognitionBreedCtx, {
                type: 'bar',
                data: {
                    labels: [],
                    datasets: [{
                        label: '识别次数',
                        data: [],
                        backgroundColor: '#F59E0B',
                        borderRadius: 4
                    }]
                },
                options: {
                    indexAxis: 'y',
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            display: false
                        },
                        tooltip: {
                            backgroundColor: 'rgba(0, 0, 0, 0.7)',
                            padding: 10,
                            cornerRadius: 8
                        }
                    },
                    scales: {
                        x: {
                            beginAtZero: true,
                            grid: {
                                color: 'rgba(0, 0, 0, 0.05)'
                            }
                        },
                        y: {
                            grid: {
                                display: false
                            },
                            ticks: {
                                maxRotation: 0,
                                autoSkip: true,
                                maxTicksLimit: 6
                            }
                        }
                    },
                    barPercentage: 0.6,
                    categoryPercentage: 0.7
                }
            });
        }

        // 更新趋势图
        function updateTrendChart(type) {
            if (!trendChart) return;
            
            const datasets = trendChart.data.datasets;
            
            switch(type) {
                case 'users':
                    datasets[0].hidden = false;
                    datasets[1].hidden = true;
                    datasets[2].hidden = true;
                    break;
                case 'content':
                    datasets[0].hidden = true;
                    datasets[1].hidden = false;
                    datasets[2].hidden = true;
                    break;
                case 'all':
                default:
                    datasets[0].hidden = false;
                    datasets[1].hidden = false;
                    datasets[2].hidden = false;
                    break;
            }
            
            trendChart.update();
        }

        // 生成模拟数据
        function generateMockData(startDate, endDate) {
            // 解析日期
            const start = new Date(startDate);
            const end = new Date(endDate);
            const days = Math.ceil((end - start) / (1000 * 60 * 60 * 24)) + 1;
            
            // 生成日期标签
            const labels = [];
            for (let i = 0; i < days; i++) {
                const date = new Date(start);
                date.setDate(start.getDate() + i);
                labels.push(formatDate(date));
            }
            
            // 生成每日统计数据
            const dailyStats = labels.map(date => {
                return {
                    date: date,
                    userCount: Math.floor(Math.random() * 50) + 20, // 20-70新增用户
                    postCount: Math.floor(Math.random() * 100) + 50, // 50-150新增内容
                    recognitionCount: Math.floor(Math.random() * 200) + 100, // 100-300识别次数
                    commentCount: Math.floor(Math.random() * 80) + 30, // 30-110评论数
                    likeCount: Math.floor(Math.random() * 200) + 50 // 50-250点赞数
                };
            });
            
            // 计算总计数据
            const totalUsers = dailyStats.reduce((sum, stat) => sum + stat.userCount, 0);
            const totalPosts = dailyStats.reduce((sum, stat) => sum + stat.postCount, 0);
            const totalRecognitions = dailyStats.reduce((sum, stat) => sum + stat.recognitionCount, 0);
            
            // 生成内容分布数据
            const contentDistribution = {
                categories: labels,
                postCounts: dailyStats.map(stat => stat.postCount),
                commentCounts: dailyStats.map(stat => stat.commentCount),
                likeCounts: dailyStats.map(stat => stat.likeCount)
            };
            
            // 生成社区活跃度数据
            const activeCommunities = Math.floor(Math.random() * 20) + 30; // 30-50个活跃社区
            const totalCommunities = activeCommunities + Math.floor(Math.random() * 10) + 5; // 额外5-15个非活跃社区
            const communityActivity = {
                labels: ['活跃社区', '非活跃社区'],
                values: [activeCommunities, totalCommunities - activeCommunities]
            };
            
            // 生成AI识别数据
            const aiRecognitionData = {
                breedLabels: ['拉布拉多', '金毛', '哈士奇', '柯基', '萨摩耶', '泰迪', '比熊', '边境牧羊犬'],
                breedCounts: [120, 95, 88, 76, 65, 54, 45, 38]
            };
            
            return {
                totalUsers: totalUsers,
                todayNewUsers: Math.floor(Math.random() * 100) + 30, // 30-130今日新增用户
                totalPosts: totalPosts,
                totalRecognitions: totalRecognitions,
                todayRecognitions: Math.floor(Math.random() * 300) + 100, // 100-400今日识别次数
                recognitionAccuracy: Math.random() * 15 + 85, // 85-100%准确率
                recognitionInterceptRate: Math.random() * 5 + 2, // 2-7%拦截率
                averageRecognitionTime: Math.random() * 1 + 0.5, // 0.5-1.5秒平均识别时间
                activeCommunities: activeCommunities,
                totalCommunities: totalCommunities,
                dailyStats: dailyStats,
                contentDistribution: contentDistribution,
                communityActivity: communityActivity,
                aiRecognitionData: aiRecognitionData,
                userGrowthRate: `${(Math.random() * 20 + 5).toFixed(1)}%`, // 5-25%增长率
                newUserGrowthRate: `${(Math.random() * 30 + 10).toFixed(1)}%`, // 10-40%增长率
                contentGrowthRate: `${(Math.random() * 15 + 8).toFixed(1)}%`, // 8-23%增长率
                recognitionGrowthRate: `${(Math.random() * 25 + 12).toFixed(1)}%` // 12-37%增长率
            };
        }
        
        // 加载仪表盘数据
        async function loadDashboardData(startDate, endDate) {
            try {
                showLoading('正在加载数据...');
                
                // 模拟API调用延迟
                await new Promise(resolve => setTimeout(resolve, 500));
                
                // 发送请求获取数据
                let dashboardData;
                try {
                    const response = await fetch(`/api/admin/dashboard/statistics?startDate=${startDate}&endDate=${endDate}&indicators=all`);
                    
                    if (!response.ok) {
                        // 如果API调用失败，使用模拟数据
                        dashboardData = generateMockData(startDate, endDate);
                    } else {
                        const data = await response.json();
                        if (!data || !data.data) {
                            // 如果API返回无数据，使用模拟数据
                            dashboardData = generateMockData(startDate, endDate);
                        } else {
                            dashboardData = data.data;
                        }
                    }
                } catch (error) {
                    // 网络错误时使用模拟数据
                    dashboardData = generateMockData(startDate, endDate);
                }
                
                // 更新页面数据
                updateDashboardData(dashboardData);
                hideLoading();
            } catch (error) {
                hideLoading();
                showErrorToast(error.message);
            }
        }

        // 更新仪表盘数据
        function updateDashboardData(dashboardData) {
            // 更新核心指标卡片
            document.getElementById('total-users').textContent = formatNumber(dashboardData.totalUsers || 0);
            document.getElementById('today-new-users').textContent = formatNumber(dashboardData.todayNewUsers || 0);
            document.getElementById('total-content').textContent = formatNumber(dashboardData.totalPosts || 0);
            document.getElementById('total-recognitions').textContent = formatNumber(dashboardData.totalRecognitions || 0);
            document.getElementById('today-recognitions').textContent = formatNumber(dashboardData.todayRecognitions || 0);
            document.getElementById('recognition-accuracy').textContent = `${(dashboardData.recognitionAccuracy || 0).toFixed(1)}%`;
            document.getElementById('intercept-rate').textContent = `${(dashboardData.recognitionInterceptRate || 0).toFixed(1)}%`;
            document.getElementById('avg-recognition-time').textContent = `${(dashboardData.averageRecognitionTime || 0).toFixed(2)}s`;
            document.getElementById('active-community-count').textContent = formatNumber(dashboardData.activeCommunities || 0);
            document.getElementById('inactive-community-count').textContent = formatNumber((dashboardData.totalCommunities || 0) - (dashboardData.activeCommunities || 0));
            
            // 更新增长率数据
            document.getElementById('user-growth-rate').textContent = dashboardData.userGrowthRate || '--';
            document.getElementById('new-user-growth-rate').textContent = dashboardData.newUserGrowthRate || '--';
            document.getElementById('content-growth-rate').textContent = dashboardData.contentGrowthRate || '--';
            document.getElementById('recognition-growth-rate').textContent = dashboardData.recognitionGrowthRate || '--';

            // 移除骨架屏效果
            document.querySelectorAll('.skeleton').forEach(el => {
                el.classList.remove('skeleton');
            });

            // 更新趋势图
            if (dashboardData.dailyStats && Array.isArray(dashboardData.dailyStats)) {
                const labels = dashboardData.dailyStats.map(stat => stat.date);
                const userData = dashboardData.dailyStats.map(stat => stat.userCount || 0);
                const postData = dashboardData.dailyStats.map(stat => stat.postCount || 0);
                const recognitionData = dashboardData.dailyStats.map(stat => stat.recognitionCount || 0);
                
                trendChart.data.labels = labels;
                trendChart.data.datasets[0].data = userData;
                trendChart.data.datasets[1].data = postData;
                trendChart.data.datasets[2].data = recognitionData;
                trendChart.update();
            }

            // 更新社区活跃度饼图
            if (dashboardData.communityActivity) {
                communityPieChart.data.datasets[0].data = dashboardData.communityActivity.values || [0, 0];
                communityPieChart.update();
            } else {
                const activeCommunities = dashboardData.activeCommunities || 0;
                const totalCommunities = dashboardData.totalCommunities || 0;
                communityPieChart.data.datasets[0].data = [activeCommunities, totalCommunities - activeCommunities];
                communityPieChart.update();
            }

            // 更新内容分布柱状图
            if (dashboardData.contentDistribution) {
                contentDistributionChart.data.labels = dashboardData.contentDistribution.categories || [];
                contentDistributionChart.data.datasets[0].data = dashboardData.contentDistribution.postCounts || [];
                contentDistributionChart.data.datasets[1].data = dashboardData.contentDistribution.commentCounts || [];
                contentDistributionChart.data.datasets[2].data = dashboardData.contentDistribution.likeCounts || [];
                contentDistributionChart.update();
            }

            // 更新识别品种分布图
            if (dashboardData.aiRecognitionData && dashboardData.aiRecognitionData.breedLabels && dashboardData.aiRecognitionData.breedCounts) {
                // 只显示前5个品种
                const topLabels = dashboardData.aiRecognitionData.breedLabels.slice(0, 5);
                const topCounts = dashboardData.aiRecognitionData.breedCounts.slice(0, 5);
                
                recognitionBreedChart.data.labels = topLabels;
                recognitionBreedChart.data.datasets[0].data = topCounts;
                recognitionBreedChart.update();
            }
        }

        // 数字格式化
        function formatNumber(num) {
            if (num >= 10000) {
                return (num / 10000).toFixed(1) + 'w';
            } else if (num >= 1000) {
                return (num / 1000).toFixed(1) + 'k';
            }
            return num.toString();
        }

        // 初始化页面
        function initPage() {
            // 初始化图表
            initCharts();
            
            // 加载默认数据
            loadDashboardData(customStartDate.value, customEndDate.value);
        }

        // 关闭提示弹窗事件
        closeErrorToast.addEventListener('click', hideErrorToast);
        closeSuccessToast.addEventListener('click', hideSuccessToast);

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', initPage);
    </script>
</body>
</html>